package org.example.login;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.ai.util.AuthContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;



@Aspect
@Component
public class RedisTokenLookupAspect {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Around("@annotation(redisTokenLookup)")
    public Object lookupToken(ProceedingJoinPoint joinPoint, RedisTokenLookup redisTokenLookup) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("Token");
            if (token != null) {
                String id = redisTemplate.opsForValue().get(token);
                if (id != null) {
                    // 这里可以将id传递给目标方法，例如通过修改参数
//                    Object[] args = joinPoint.getArgs();
                    AuthContextHolder.setUserId(Long.valueOf(id));
                    // 假设目标方法的第一个参数是用于接收id的
//                    args[0] = id;
                    return joinPoint.proceed();
                }
            }
        }
        return joinPoint.proceed();
    }
}
